// ActivityRegister.java
package com.sadam.ui4;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;
import com.sadam.ui4.Data.MySqLiteOpenHelper;
import com.sadam.ui4.Data.User;
import com.sadam.ui4.Utils.ValidationUtils;

import java.util.List;

public class ActivityRegister extends AppCompatActivity {

    private MySqLiteOpenHelper mySqLiteOpenHelper;
    private TextInputEditText usernameEditText;
    private TextInputEditText verificationCodeEditText;   // 密码输入框
    private TextInputEditText confirmPasswordEditText;    // 确认密码输入框

    private TextInputLayout confirmPasswordInputLayout;   // 用于显示错误提示

    private Button registerButton;
    private TextView loginGuideText;
    private View loadingProgressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);

        // 初始化数据库帮助类
        mySqLiteOpenHelper = new MySqLiteOpenHelper(this, MySqLiteOpenHelper.DATABASE_NAME, null, MySqLiteOpenHelper.DATABASE_VERSION);

        // 绑定控件
        usernameEditText = findViewById(R.id.usernameEditText);
        verificationCodeEditText = findViewById(R.id.verificationCodeEditText);
        confirmPasswordEditText = findViewById(R.id.confirmPasswordEditText);

        confirmPasswordInputLayout = findViewById(R.id.confirmPasswordInputLayout); // 用于 setError 显示

        registerButton = findViewById(R.id.registerButton);
        loginGuideText = findViewById(R.id.loginGuideText);
        loadingProgressBar = findViewById(R.id.loadingProgressBar);

        // 实时校验：当用户输入确认密码时，动态检查是否一致
        confirmPasswordEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}

            @Override
            public void afterTextChanged(Editable s) {
                String password = verificationCodeEditText.getText().toString();
                String confirm = s.toString();

                if (!confirm.isEmpty() && !password.equals(confirm)) {
                    confirmPasswordInputLayout.setError("两次输入的密码不一致");
                } else {
                    confirmPasswordInputLayout.setError(null);
                }
            }
        });

        // 注册按钮点击事件
        registerButton.setOnClickListener(v -> {
            String username = usernameEditText.getText().toString().trim();
            String password = verificationCodeEditText.getText().toString().trim();
            String confirmPassword = confirmPasswordEditText.getText().toString().trim();

            // 调用 ValidationUtils 进行批量校验（包含确认密码一致性）
            List<String> errors = ValidationUtils.validateRegistration(username, password, confirmPassword);

            if (!errors.isEmpty()) {
                showValidationErrorDialog(errors);
                return;
            }

            setLoading(true);

            // 尝试注册用户
            User user = User.register(mySqLiteOpenHelper, username, password);
            if (user != null) {
                Toast.makeText(this, "注册成功", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(ActivityRegister.this, ActivityLogin.class);
                startActivity(intent);
                finish(); // 关闭当前页面
            } else {
                showSingleErrorDialog("注册失败", "该用户名已被使用，请换一个用户名。");
            }

            setLoading(false);
        });

        // 登录引导点击事件
        loginGuideText.setOnClickListener(v -> {
            Intent intent = new Intent(ActivityRegister.this, ActivityLogin.class);
            startActivity(intent);
            finish();
        });
    }

    /**
     * 显示多个验证错误的对话框
     */
    private void showValidationErrorDialog(List<String> errors) {
        StringBuilder message = new StringBuilder("请修正以下问题：\n\n");
        for (int i = 0; i < errors.size(); i++) {
            message.append(i + 1).append(". ").append(errors.get(i)).append("\n");
        }

        new AlertDialog.Builder(this)
                .setTitle("输入格式错误")
                .setMessage(message.toString())
                .setPositiveButton("确定", (dialog, which) -> dialog.dismiss())
                .setCancelable(false)
                .show();
    }

    /**
     * 显示单一错误对话框（如用户名已存在）
     */
    private void showSingleErrorDialog(String title, String message) {
        new AlertDialog.Builder(this)
                .setTitle(title)
                .setMessage(message)
                .setPositiveButton("确定", (dialog, which) -> dialog.dismiss())
                .setCancelable(false)
                .show();
    }

    /**
     * 设置加载状态
     */
    private void setLoading(boolean loading) {
        loadingProgressBar.setVisibility(loading ? View.VISIBLE : View.GONE);
        registerButton.setEnabled(!loading);
    }
}